<?php
namespace Common\Api;
use Think\Controller;
use Common\Model\LeavelModel;
use Common\Model\UserModel;
use Common\Model\UserMoneyModel;
use Common\Model\CurrencyModel;
use Common\Model\ConfigModel;
use Common\Model\BonusLogModel;
use Common\Model\FinanceLogModel;
use Common\Model\RewardTypeModel;
class Reward extends Controller {
    public static function newSelf($user,$num)
    {
        return new self($user,$num);
    }
    
    private $leavel_sys;
    private $user_info;
    private $__USER;
    private $__USER_MONEY;
    private $reward_currency;
    private $web_config;
    private $tree;
    private $num;
    private $reward_type;
    
    public function __construct($user_id,$num)
    {
        ignore_user_abort(true);
        set_time_limit(0); 
        parent::__construct();
        $this->leavel_sys=LeavelModel::newSelf()->getInfo();
        $this->__USER=UserModel::newSelf();
        $this->user_info=$this->__USER->findUserByUserId($user_id);
        $this->__USER_MONEY=UserMoneyModel::newSelf();
        $this->reward_currency=CurrencyModel::newSelf()->findRewardCurrency();
        $this->web_config=ConfigModel::newSelf()->getInfo();
        $this->num=$num;
        $this->reward_type=RewardTypeModel::newSelf()->getInfo();
    }
    public function initialTree()
    {
        $this->tree=$this->__USER->findUpUser($this->user_info['jie_id']);
        
    }
    public function tuijianjiang()
    {
        $type='1';
        $tui_user=$this->__USER->findUserByUserId($this->user_info['tui_id']);
        if (!$this->checkUserCanRewardRule($tui_user))
        {
            return false;
        }
        $base_num=$this->num;
        $num=$this->getRewardNum($tui_user['id'],$tui_user['leavel'],$type,$base_num);
            
        if ($num>0) 
        {
            $this->giveAwayReward($tui_user['id'],$num,$type);
        }
        
    }
//     public function anzhijiang()
//     {
//         $type='4';
        
//         if ($this->user_info['jie_id']==$this->user_info['tui_id']) {
//             return true;
//         }
//         $tui_user=$this->__USER->findUserByUserId($this->user_info['jie_id']);
//         if (!$this->checkUserCanRewardRule($tui_user))
//         {
//             return false;
//         }
//         $base_num=$this->num;
//         $num=$this->getRewardNum($tui_user['id'],$tui_user['leavel'],$type,$base_num);
//         if ($num>0) 
//         {
//             $this->giveAwayReward($tui_user['id'],$num,$type);
//         }
        
//     }
    public function jiandianjiang()
    {
        $type='2';
        $base_num=$this->num;
        foreach ($this->tree as $k=>$v)
        {
            if ($k+1>$this->leavel_sys[$v['leavel']]['ratio'][4]['num'])
            {
                continue;
            }
            if (!$this->checkUserCanRewardRule($v))
            {
                continue;
            }
            $num=$this->getRewardNum($v['id'],$v['leavel'],$type,$base_num);
            if ($num>0) 
            {
                $this->giveAwayReward($v['id'],$num,$type);
            }
        }
    }
    public function duipeng()
    {
    	$User=UserModel::newSelf();
        $type='3';
        $quyu=$this->user_info['quyu'];
        foreach ($this->tree as $k=>$v)
        {
        	$tui_user_count=$User->findUserTuiNum($this->tree[$k]['id']);
        	if($tui_user_count<2){
        		continue;
        	}
        	
            if ($this->tree[$k-1]) 
            {
                $quyu=$this->tree[$k-1]['quyu'];
            }
            if (!$this->checkUserCanRewardRule($v))
            {
                continue;
            }
            $money=$this->num;
            $this->__USER->incUserYeji($v['id'],$quyu,$money,'all_');
            $yeji=0;
            if ($quyu=='1') {
                if ($v['yeji2']>0&&$v['yeji3']==0) {
                    $yeji=$v['yeji2'];
                    $dec_quyu='2';
                }
                if ($v['yeji2']==0&&$v['yeji3']>0) {
                    $yeji=$v['yeji3'];
                    $dec_quyu='3';
                }
                $base_num=min($yeji,$money);
            }
            if ($quyu=='2') {
                if ($v['yeji1']>0&&$v['yeji3']==0) {
                    $yeji=$v['yeji1'];
                    $dec_quyu='1';
                }
                if ($v['yeji1']==0&&$v['yeji3']>0) {
                    $yeji=$v['yeji3'];
                    $dec_quyu='3';
                }
                $base_num=min($yeji,$money);
            }

            if ($base_num>0) 
            {
                $num=$this->getRewardNum($v['id'],$v['leavel'],$type,$base_num);
                if ($num>0) 
                {
//                     $this->fendoujiang($v,$num);
                    $this->giveAwayReward($v['id'],$num,$type);
                }
                $this->__USER->decUserYeji($v['id'],$dec_quyu,$base_num);
                if ($money-$base_num>0) 
                {
                    $this->__USER->incUserYeji($v['id'],$quyu,$money-$base_num);
                }
            }
            else
            {
                $this->__USER->incUserYeji($v['id'],$quyu,$money);
            }
        }
    }
    public function fendoujiang($user,$base_num)
    {
        $type=4;
        $up=$this->__USER->findUpUser($user['jie_id'],4);
        foreach ($up as $k=>$v)
        {
            if ($k>=4) {
                break;
            }
            if (!$this->checkUserCanRewardRule($v))
            {
                continue;
            }
            $num=$this->getRewardNum($v['id'],$v['leavel'],$type,$base_num);
    
            if ($num>0)
            {
                $this->giveAwayReward($v['id'],$num,$type);
            }
            
        }
        
    }
    public function checkUserCanRewardRule($user)
    {
//         if ($user['status']=='0') 
//         {
//             return false;
//         }
        if ($user['lock']=='1')
        {
            return false;
        }
        return true;
    }
    private function getRewardNum($user_id,$leavel,$type,$base_money='')
    {    	
        $leavel_ratio=$this->leavel_sys[$leavel]['ratio'][$type];
        if (!$leavel_ratio) 
        {
            return 0;
        }
        $ratio_type=$this->reward_type[$leavel_ratio['reward_type']]['type'];

        if ($ratio_type=='num') 
        {
            $num=$leavel_ratio['num'];
        }
        if ($ratio_type=='ratio')
        {
            $num=$leavel_ratio['ratio']*$base_money;
        }
//         $user_money=$this->__USER_MONEY->findUserMoneyInfoByMoneyId($user_id,'9');
//         $num=min($num,$user_money['num']);
        
        $time=strtotime(date('Y-m-d',time()));
        $bonus_model=BonusLogModel::newSelf();
        $log=$bonus_model->findByAddTimeAndUserId($time,$user_id);
        if ($log)
        {
            $num=min(($this->leavel_sys[$leavel]['day_max_reward']-$log['bonus6']),$num);
        }
        return $num;
    }
    private function giveAwayReward($user_id,$num,$type)
    {
        $bonus_id=$this->reward_type[$type]['bonus_type'];
        $data['bonus'.$bonus_id]=$num;
        $data['bonus6']=$num;
//         $data['bonus7']=$num*$this->web_config['reward_fee'];
        $finance=FinanceLogModel::newSelf();
//         $this->__USER_MONEY->decUserMoney($user_id,9, $num);
        foreach ($this->reward_currency as $k=>$v)
        {
//             if ($v['id']=='5') 
//             {
//                 $data['bonus9']=$num*$v['reward_ratio'];
//             }
            $this->__USER_MONEY->incUserMoney($user_id,$v['id'],$num*$v['reward_ratio']);
            $res[]=$finance->addLog($type,$num*$v['reward_ratio'],$user_id,$v['id'],$this->user_info['id']);
        }
        $bonus_id=$this->updateBonusLog($user_id,$data);
        $finance->where(['id'=>['in',$res]])->setField('bonus_id',$bonus_id);
        
    }
    public function updateBonusLog($user_id,$arr)
    {
        $time=strtotime(date('Y-m-d',time())); 
        $bonus_model=BonusLogModel::newSelf();
        $log=$bonus_model->findByAddTimeAndUserId($time,$user_id);
        if ($log) 
        {
            foreach ($arr as $k=>$v)
            {
                $data[$k]=array('exp',$k.'+'.$v);
            }
            $bonus_model->where(['id'=>$log['id']])->save ( $data );
			return $log ['id'];
		} else {
			$data = $arr;
            $data['add_time']=$time;
            $data['user_id']=$user_id;
            return $bonus_model->add($data);
            
        }
    }
    
    public function guanlijiang(){
    	$money=$this->num;
        $quyu=$this->user_info['quyu'];
    	foreach($this->tree as $k=>$v){
    		$tui_user_count=$this->__USER->findUserTuiNum($v['id']);
    		if($tui_user_count<2){
    			continue;
    		}   	
            if ($this->tree[$k-1]) 
            {
                $quyu=$this->tree[$k-1]['quyu'];
            }
            $this->__USER->incUserYeji($v['id'],$quyu,$money,'all_');
            $this->__USER->incUserYeji($v['id'],$quyu,$money);
    	}
    }
}